const express = require('express');
const router = express.Router();
const User = require('../src/model/user')
const LogWrite = require('../utils/logger')
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

function hashPassword(password, a) {
  const salt = a || bcrypt.genSaltSync(); // 生成盐值  
  const newPassword = bcrypt.hashSync(password, salt); // 对密码进行哈希处理  
  return { newPassword, salt };
}

router.post('/register', function (req, res) {
  const { username, password } = req.body
  const { newPassword, salt } = hashPassword(password)

  User.create({
    username,
    password: newPassword,
    salt: salt,
    register_time: new Date().toLocaleString()
  }).then(function (result) {
    res.send({
      code: "YES",
      msg: "注册成功!"
    })
  }).catch(function (err) {
    res.send({
      code: "NO",
      msg: "注册失败!" + err
    })
  })
});

router.post('/login', async (req, res) => {
  const { username, password } = req.body;

  const result = await User.findOne({
    where: {
      username: username
    },
    raw: true
  })
  const { newPassword } = hashPassword(password, result.salt)

  if (result.password === newPassword) {
    // 创建token
    const token = jwt.sign(result, 'app.get(superSecret)', {
      expiresIn: 1440 // 设置过期时间
    })
    // json格式返回token 
    res.json({
      code: "YES",
      msg: '登陆成功!',
      token: token
    });
  } else {
    res.send({
      code: "NO",
      msg: "登录失败!"
    })
  }
})

module.exports = router;
